package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.commons.ServerResponse;
import com.chixing.config.AlipayConfig;
import com.chixing.pojo.Myorders;
import com.chixing.pojo.PersonFlow;
import com.chixing.service.IMyordersService;
import com.chixing.service.IPersonFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * 流水表 前端控制器
 * </p>
 *
 * @author Jason Marslyon
 * @since 2022-10-04
 */
@Controller
public class PersonFlowController {

    @Autowired
    private IMyordersService myordersService;

    @Autowired
    public IPersonFlowService personFlowService;

    @PostMapping("personFlow/selectById")
    @ResponseBody
    public String selectById(@RequestParam("templateId") Integer templateId,
                             @RequestParam("orderId")Integer orderId,
                             @RequestParam("orderNumber")String orderNumber,
                             @RequestParam("orderPrice")String orderPrice,
                             @RequestParam("templateName")String templateName) {
        Myorders myorders = myordersService.selectById(orderId);
        if (myorders == null) {
            return "<a href = 'http://localhost:8080/link/public/resume/resume-template-home.jsp'>订单已经超时，请重新下单。</a>";
        } else {
            //1.初始化AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);
            //2.设置请求参数，return  url
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = orderNumber;
            //付款金额，必填
            Float total_amount = Float.parseFloat(orderPrice);
            //订单名称，必填
            String subject = templateName + "模板";
            //商品描述，可空


            // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
            String timeout_express = "1c";

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"timeout_express\":\"" + timeout_express + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            System.out.println(templateId);
            //请求
            String result = null;
            try {
                result = alipayClient.pageExecute(alipayRequest).getBody();
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            System.out.println("result:" + result);
            return result;
        }
    }
    //支付宝支付成功后，需要调用的业务处理（1.添加流水 2.修改订单）
    //流水支付状态默认为空，不设值，可删除该字段
    //同步请求
    @RequestMapping("alipayReturnNotice")
    @ResponseBody
    public ModelAndView returnNotice(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        System.out.println("支付成功的数据：" + request);
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requesParams = request.getParameterMap();
        for (Iterator<String> iterator = requesParams.keySet().iterator(); iterator.hasNext(); ) {
            String name =  iterator.next();
            String[] values =  requesParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            System.out.println("========"+params);
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            System.out.println(signVerified);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        ModelAndView mv = new ModelAndView("public/resume/resume-success");
        if(!signVerified) {
            //1.添加流水 2.修改订单

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            // String proId = new String(request.getParameter("product_id").getBytes("ISO-8859-1"),"UTF-8");
            // String proNum = new String(request.getParameter("proNum").getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("交易号"+total_amount);
            PersonFlow flow = new PersonFlow();
            //flow.setId(UUID.randomUUID().toString().replace("-",""));
            flow.setFlowNumber(trade_no);
            flow.setText1(out_trade_no);
            //flow.setProductId(product_id);
            //flow.setBuyCounts(Integer.valueOf(proNum));
            //flow.setProductId(proId);
            flow.setPayCreateTime(LocalDateTime.now());
            System.out.println("===========================");
            flow.setPayPrice(Float.parseFloat(total_amount));
            ServerResponse save = personFlowService.insert(flow);
            ModelAndView mav=new ModelAndView();
            mav.addObject("result",save);
            mav.setViewName("public/resume/resume-success");
            return mav;
        }else{
            return null;
        }
    }
    //异步请求
    @RequestMapping("alipayNotifyNotice")
    @ResponseBody
    public ModelAndView notifyNotice(HttpServletRequest request, HttpServletResponse response){
        return null;
    }

}
